package com.atguigu.spzx.service.impl;

import cn.hutool.Hutool;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.atguigu.spzx.constant.CacheConstant;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import com.atguigu.spzx.service.ValidateCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
@Transactional
public class ValidateCodeServiceImp implements ValidateCodeService {

    @Autowired
    RedisTemplate<String, String> redisTemplate;


    @Override

    public ValidateCodeVo generateValidateCode() {
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 10);
        String code = circleCaptcha.getCode();
        String key = UUID.randomUUID().toString().replace("-", "");
        String imageBase64 = circleCaptcha.getImageBase64();
        redisTemplate.opsForValue().set(CacheConstant.USER_LOGIN_VALIDATECODE_PREFIX + key, code, 1, TimeUnit.MINUTES);
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(key);
        validateCodeVo.setCodeValue(CacheConstant.USER_LOGIN_VALIDATECODE_IMAGE_PREFIX + imageBase64);
        return validateCodeVo;
    }
}
